#include "imagedialog.h"
#include "ui_imagedialog.h"

#include <QPainter>
#include <QThread>
#include <QUuid>

ImageDialog::ImageDialog(QWidget *parent, bool isNew) :
    QDialog(parent),
    ui(new Ui::ImageDialog)
{
    ui->setupUi(this);
    ui->lbImage->setScaledContents(true);
    ui->lbImage->clear();

    if(isNew){
        id = QUuid::createUuid().toString(QUuid::StringFormat::WithoutBraces);
        qDebug() << "create id: " << id;
    }

}

ImageDialog::ImageDialog(QString id, QString imgFileName, QWidget *parent): ImageDialog(parent, false)
{
    this->id = id;
    setImage(imgFileName);
}

ImageDialog::~ImageDialog()
{
    delete ui;
}

void ImageDialog::setImage(QString afile)
{
    QImage image(afile);
    aimage = QPixmap::fromImage(image);
    this->imgFileName = afile;
}

ImageInfo ImageDialog::getImageInfo()
{
    auto s = this->size();
    auto p = this->pos();

    ImageInfo info{
        id,
        imgFileName,
        {s.width(), s.height()},
        {p.x(), p.y()}
    };

    return info;
}

const QString &ImageDialog::getId() const
{
    return id;
}

void ImageDialog::doSave()
{
    auto info = this->getImageInfo();
    this->saveWork.doSaveWork((info));
//    SaveWork::doSaveWork(info);
}

void ImageDialog::resizeEvent(QResizeEvent *event)
{
    doSave();
    QSize winSize = size();
    imageHeight = aimage.height();
    imageWidth  = aimage.width();

    if (imageHeight  > winSize.height()) {
        double heightRatio = (double)winSize.height() / aimage.height();
        imageHeight = (int)(aimage.height() * heightRatio);
        imageWidth  = (int)(aimage.width()  * heightRatio);
    }

    if (imageWidth > winSize.width()) {
        double widthRatio = (double)winSize.width() / imageWidth;
        imageHeight = (int)(imageHeight * widthRatio);
        imageWidth  = (int)(imageWidth  * widthRatio);
    }

    widthOffset  = winSize.width()  > imageWidth  ? ((winSize.width()  - imageWidth)  / 2) : 0;
    heightOffset = winSize.height() > imageHeight ? ((winSize.height() - imageHeight) / 2) : 0;
}

void ImageDialog::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(widthOffset, heightOffset, imageWidth, imageHeight, aimage);
}

void ImageDialog::moveEvent(QMoveEvent *event)
{
    doSave();
}

